package com.fzrskj.cloud.free.user.service;

import com.fzrskj.cloud.free.consts.CConsts;
import com.fzrskj.cloud.free.core.enums.DicParamEnum;
import com.fzrskj.cloud.free.core.enums.MessageSendWayEnum;
import com.fzrskj.cloud.free.core.tool.*;
import com.fzrskj.cloud.free.core.utils.EncryptUtils;
import com.fzrskj.cloud.free.core.utils.SessionUtils;
import com.fzrskj.cloud.free.dic.utils.DicParamUtils;
import com.fzrskj.cloud.free.sys.bean.Cookies;
import com.fzrskj.cloud.free.sys.utils.SendMailUtils;
import com.fzrskj.cloud.free.sys.utils.SendSMSUtils;
import com.fzrskj.cloud.free.user.bean.UserAccount;
import com.fzrskj.cloud.free.user.utils.UserLogUtils;
import com.fzrskj.cloud.free.user.utils.UserAccountUtils;
import com.fzrskj.cloud.free.user.bean.UserAccountView;
import ms.core.consts.SysErr;
import ms.core.object.CObject;
import ms.core.support.Session;
import ms.core.tool.CookieTool;
import ms.core.tool.JsonTool;
import ms.core.tool.StrTool;
import ms.core.tool.XmlCodeParser;
import org.apache.commons.collections.map.HashedMap;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * UserCodeLoginService.
 *
 * @author zj.
 *         Created on 2018/12/17 0017.
 */
public class UserCodeLoginService extends CObject {
    /**
     * 获取登录验证码.
     * @param request
     * @param response
     * @param p
     * @param sid
     * @return
     */
    public String getLoginCode(HttpServletRequest request, HttpServletResponse response, String p, String sid){
        String flagSupport = DicParamUtils.getParamValue(DicParamEnum.SUPPORT_CODE_LOGIN.getVal());
        if (!"2".equals(flagSupport)) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR, "当前不支持验证码登录");
        }
        String account = JsonTool.getStrValue(p, "userName", "");
        if (StrTool.isBlankStr(account)) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
        }

        UserAccountView accountView = this.getAccountView(account);

        if (null == accountView) {
            return XmlCodeParser.formatResultTips(false, SysErr.USER_NOT_EXISTS);
        }

        String code = CStrTool.randNum(6);
        SessionUtils.set(CConsts.CODE_LOGIN_SESSION_NAME, code);

        List<NameValuePair> messageParams = new ArrayList<NameValuePair>();
        messageParams.add(new BasicNameValuePair("\\[验证码\\]", code));

        //获取配置参数
        String sendWay = DicParamUtils.getParamValue(DicParamEnum.CODE_LOGIN_WAY.getVal());
        if (MessageSendWayEnum.MAIL.equals(sendWay)) {
            SendMailUtils mailUtils = new SendMailUtils();
            mailUtils.loadWebsiteParam(messageParams);
            mailUtils.sendMail("userCodeLoginMail", accountView.getEmail(), messageParams);
        } else if (MessageSendWayEnum.SMS.equals(sendWay)) {
            Map<String,Object> map = new HashedMap();
            map.put("userId", accountView.getUserId());
            map.put("mobile", accountView.getMobile());

            SendSMSUtils smsUtils = new SendSMSUtils();
            smsUtils.loadWebsiteParam(messageParams);
            smsUtils.sendSMS("userCodeLoginSms", map, messageParams);
        } else {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_DATA_NOT_FOUND, "系统参数配置错误");
        }

        return XmlCodeParser.formatResultTips(true, SysErr.CODE_SUCCESS);
    }

    public String getRegisterCodeNew(HttpServletRequest request, HttpServletResponse response, String p, String sid){
        String account = JsonTool.getStrValue(p, "userName", "");
        String type = JsonTool.getStrValue(p, "type", "");
        if (StrTool.isBlankStr(account) || StrTool.isBlankStr(type)) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
        }
        String code = CStrTool.randNum(6);

        List<NameValuePair> messageParams = new ArrayList<NameValuePair>();
        messageParams.add(new BasicNameValuePair("\\[验证码\\]", code));

        if (MessageSendWayEnum.MAIL.equals(type)) {
            if(!CVerificationTool.isMail(account)){
                return XmlCodeParser.formatResultTips(false, SysErr.SYS_DATA_NOT_FOUND, "邮箱账号格式不正确");
            }

            UserAccountUtils accountUtils = new UserAccountUtils();
            UserAccount userAccount = accountUtils.isRegisterEmail(account);
            if (null != userAccount) {
                return XmlCodeParser.formatResultTips(false, SysErr.SYS_DATA_EXISTS, "该邮箱已被其他账号关联注册");
            }

            SessionUtils.set(CConsts.CODE_AUTH_EMAIL_SESSION_NAME, code + "|" + account);
            SendMailUtils mailUtils = new SendMailUtils();
            mailUtils.loadWebsiteParam(messageParams);
            mailUtils.sendMail("userCodeLoginMail", account, messageParams);
        } else if (MessageSendWayEnum.MOBILE.equals(type)) {
            if(!CVerificationTool.isMobileNO(account)){
                return XmlCodeParser.formatResultTips(false, SysErr.SYS_DATA_NOT_FOUND, "电话号码格式不正确");
            }

            UserAccountUtils accountUtils = new UserAccountUtils();
            UserAccountView userAccount = accountUtils.isRegisterMobile(account, 0);
            if (null != userAccount) {
                return XmlCodeParser.formatResultTips(false, SysErr.SYS_DATA_EXISTS, "该手机号已被其他账号关联注册");
            }

            SessionUtils.set(CConsts.CODE_AUTH_MOBILE_SESSION_NAME,  code + "|" + account);
            Map<String,Object> map = new HashedMap();
            map.put("userId", account);
            map.put("mobile", account);

            SendSMSUtils smsUtils = new SendSMSUtils();
            smsUtils.loadWebsiteParam(messageParams);
            smsUtils.sendSMS("userCodeLoginSms", map, messageParams);
        } else {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_DATA_NOT_FOUND, "系统参数配置错误");
        }
        return XmlCodeParser.formatResultTips(true, SysErr.CODE_SUCCESS);
    }

    public String getRegisterCode(HttpServletRequest request, HttpServletResponse response, String p, String sid){
        String account = JsonTool.getStrValue(p, "userName", "");
        if (StrTool.isBlankStr(account)) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
        }
        String code = CStrTool.randNum(6);
        SessionUtils.set(CConsts.CODE_LOGIN_SESSION_NAME, code);

        List<NameValuePair> messageParams = new ArrayList<NameValuePair>();
        messageParams.add(new BasicNameValuePair("\\[验证码\\]", code));
        String sendWay = DicParamUtils.getParamValue(DicParamEnum.CODE_LOGIN_WAY.getVal());
        if (MessageSendWayEnum.MAIL.equals(sendWay)) {
            if(!CVerificationTool.isMail(account)){
                return XmlCodeParser.formatResultTips(false, SysErr.SYS_DATA_NOT_FOUND, "邮箱账号格式不正确");
            }
            SendMailUtils mailUtils = new SendMailUtils();
            mailUtils.loadWebsiteParam(messageParams);
            mailUtils.sendMail("userCodeLoginMail", account, messageParams);
        } else if ("sms".equals(sendWay)) {
            if(!CVerificationTool.isMobileNO(account)){
                return XmlCodeParser.formatResultTips(false, SysErr.SYS_DATA_NOT_FOUND, "电话号码格式不正确");
            }
            Map<String,Object> map = new HashedMap();
            map.put("userId", account);
            map.put("mobile", account);

            SendSMSUtils smsUtils = new SendSMSUtils();
            smsUtils.loadWebsiteParam(messageParams);
            smsUtils.sendSMS("userCodeLoginSms", map, messageParams);
        } else {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_DATA_NOT_FOUND, "系统参数配置错误");
        }
        return XmlCodeParser.formatResultTips(true, SysErr.CODE_SUCCESS);
    }

    /**
     * 验证码登录验证.
     * @param request
     * @param response
     * @param p
     * @param sid
     * @return
     */
    public String codeLogin(HttpServletRequest request, HttpServletResponse response, String p, String sid) {
        String flagSupport = DicParamUtils.getParamValue(DicParamEnum.SUPPORT_CODE_LOGIN.getVal());
        if (!"2".equals(flagSupport)) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR, "当前不支持验证码登录");
        }
        String account = JsonTool.getStrValue(p, "userName", "");
        String password = JsonTool.getStrValue(p, "password", "");
        if (StrTool.isBlankStr(account) || StrTool.isBlankStr(password)) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
        }
        String checkCode = EncryptUtils.decodePublic(password);
        if (StrTool.isBlankStr(checkCode)) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR, "验证码解码失败");
        }

        UserAccountView accountView = this.getAccountView(account);

        if (null == accountView) {
            return XmlCodeParser.formatResultTips(false, SysErr.USER_NOT_EXISTS);
        }

        if (!checkCode.equals(SessionUtils.get(CConsts.CODE_LOGIN_SESSION_NAME))) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR, "验证码不正确");
        }

        //登录session处理
        if (accountView.getStatus().equals(CConsts.ACCOUNT_NORMAL)){
            //set user session,it contains: user record id\ user id\ account
            int uid = accountView.getUserId();
            Session ssn = new Session();
            ssn.setId(accountView.getId());
            ssn.setUID(uid);
            ssn.setUname(accountView.getUserName());
            //set user account email
            ssn.setData(accountView.toJsonString());
            ssn.setUtype(1);
            //TODO to fill user functions
            ssn.setFuncs("");
            CSessionTool.setLoginSessionCloud(sid, ssn);
            //set user cookie,it contains: account id\account
            Cookies cks = new Cookies();
            cks.setId(accountView.getId());
            cks.setUid(uid);
            cks.setAccount(accountView.getUserName());
            cks.setUname(accountView.getUserName());
            cks.setSaid(CEncryptTool.encodeSAID(sid, uid, accountView.getUserName()));
            CookieTool.setLoginCookie(response, sid, cks);

            EncryptUtils.makeSession(response, request);


            UserLogUtils.addLog("user.login", accountView.getUserId(), "用户登录成功");
        }
        String data = CJsonTool.beanToJson(accountView);
        data = CJsonTool.delNode(data, "passWord");
        data = CJsonTool.delNode(data, "regTime");
        data = CJsonTool.delNode(data, "randomCode");
        data = CJsonTool.addNode(data, "regTime", CDateTimeTool.dateToDateString(accountView.getRegTime()));
        return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS, data);
    }

    /**
     * 获取账号信息.
     * @param account 账号.
     * @return UserAccountView.
     */
    private UserAccountView getAccountView(String account) {
        UserAccountView accountView = null;
        UserAccountUtils accountUtils = new UserAccountUtils();
        UserAccount userAccount = accountUtils.queryAccountByName(account);
        if (null == userAccount) {
            accountView = accountUtils.queryUserAccountView(account);
            if (null == accountView) {
                accountView = accountUtils.queryUserAccountViewByMobile(account);
            }
        } else {
            accountView = accountUtils.queryUserAccountViewByUid(userAccount.getUserId());
        }

        return accountView;
    }
}
